package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;

    @Override
    public PageResult<Clazz> findList(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        // 创建Page对象
        Page<Clazz> clazzPage = new Page<>(page, pageSize);

        // 拼接条件sql
        LambdaQueryWrapper<Clazz> clazzListWrapper = Wrappers.<Clazz>lambdaQuery().like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getEndDate, begin, end)
                ;

        // 获取 page列表
        clazzPage = page(clazzPage, clazzListWrapper).addOrder(OrderItem.desc("update_time"));

        // 将clazzList 中的masterName补全
        List<Clazz> clazzList = clazzPage.getRecords();

        // 提取 班主任姓名 （emp表）
        List<Emp> empList = empService.list();

        // 创建 empMap
        Map<Integer, String> empMap = empList.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));

        LocalDate now = LocalDate.now();
        // 遍历 clazzList ，为每个 clazz 补充班主任姓名
        if(clazzList != null && !clazzList.isEmpty())
        {
            clazzList.forEach(clazz -> {
                if(clazz.getMasterId() != null) {
                    clazz.setMasterName(empMap.get(clazz.getMasterId()));
                }

                // 定义 班级状态枚举
                Clazz.ClazzStatus status;

                if(now.isBefore(clazz.getBeginDate())){
                    status = Clazz.ClazzStatus.NO_START;
                } else if (now.isAfter(clazz.getEndDate())) {
                    status = Clazz.ClazzStatus.IS_STOP;
                }else {
                    status = Clazz.ClazzStatus.IN_START;
                }
                // 给班级状态赋值
                clazz.setStatus(status.getInfo());
            });
        }

        return new PageResult<>(clazzPage.getTotal(), clazzList);
    }


}
